<?php

/**
 * This is the model class for table "school".
 *
 * The followings are the available columns in table 'school':
 * @property string $id
 * @property string $cnname
 * @property string $enname
 * @property string $abbreviation
 * @property string $site
 * @property integer $create_time
 * @property string $cate
 * @property string $belong
 * @property string $icon
 * @property integer $status
 * @property string $subjects
 * @property string $code
 */
class School extends CActiveRecord {

    const STATUS_PENDING = 1;
    const STATUS_OK = 2;
    const STATUS_INVALID = 3;

    /**
     * Returns the static model of the specified AR class.
     * @return School the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'school';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        return array(
            array('cnname, abbreviation, site, code', 'required'),
            array('cnname, abbreviation, cate, belong, icon, enname, site', 'length', 'max' => 128),
        );
    }

    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'cnname' => '学校中文名',
            'enname' => '学校英文名',
            'abbreviation' => '学校简称',
            'site' => '学校官方网站',
            'create_time' => '记录创建时间',
            'cate' => '学校类别',
            'belong' => '学校所属',
            'code' => '学校代码',
        );
    }

    protected function beforeSave() {
        $this->create_time = time();
        $this->status = self::STATUS_PENDING;
        return parent::beforeSave();
    }

    public function setIconPath($id, $path){
        $school = self::model()->findByPk($id);
        $school->icon = $path;
        $school->update();
    }
    
    public function deleteSchoolById($id){
        self::model()->updateByPk($id, array('status' => self::STATUS_INVALID));
    }
    
    public function loadSchools(){
        $schools = Yii::app()->cache->get('schools');
        if(empty($schools)){
            $criteria = new CDbCriteria();
            $criteria->condition = 'status='.School::STATUS_OK;
            $schools = School::model()->findAll($criteria);
            Yii::app()->cache->set('schools', $schools);
        }
        return $schools;
    }
}